#!/usr/bin/env python
#项目名：简易版贪吃蛇
#作者： 赖宇光
#修改时间： 2017-9-11
#版本： 2.0
import time
import threading
import random
import sys, os
import vt100

x = 20
y = 5
h = 20
w = 80
xf = random.randint(2, w - 1)
yf = random.randint(2, h - 1)
k = 'd'
c = k
flag = True
snake = [[18, 5], [19,5], [20, 5]]
count = 0

def init():
    '''
    初始化终端环境（关闭回显和光标）
    '''
    vt100.cursor(0)
    os.system("stty -echo -icanon")


def foods():
    '''
    随机出现食物
    '''
    global xf, yf
    xf = random.randint(2, w - 1)
    yf = random.randint(2, h - 1)
    if [xf, yf] in snake:
        foods()


def show_bg():

    '''
    打印游戏画板
    '''

    print("\033[1;1H", end='', flush=True)

    for r in range(h):
        for c in range(w):
            if r == 0 or r == h - 1 or c == 0 or c == w - 1:
                vt100.gotoxy(r + 1, c +1, '#')
        print(flush=True)


def InputKey():
    '''
    读取键盘输入
    '''
    global c
    while flag:
        c = sys.stdin.read(1)


def Snake():
    '''
    蛇身
    '''

    global snake, food, count
    snake.append([x, y])
    vt100.selColor(33)
    if [x, y] != [xf, yf]:
        vt100.gotoxy(snake[0][1], snake[0][0], ' ')
        del snake[0]
    else:
        foods()
        count +=1


def move():
    '''
    运行的下一个位置
    '''
    global x, y, k
#调头判断
    if k == 'w' and c != "s":
        k = c
    elif k == 's' and c != 'w':
        k = c
    elif k == 'a' and c !='d' :
        k = c
    elif k == 'd' and c != 'a':
        k = c

    if k == 'w':
        y -= 1
    elif k == 's':
        y += 1
    elif k == 'a':
        x -= 1
    elif k == 'd':
        x += 1
    vt100.gotoxy(y, x, "*")

def GameOver():
    '''
    结束判断及终端环境恢复
    '''
    global flag
    if k == 'q' or x ==1 or x == w or y == 1 or y == h \
            or [x, y] in snake[0: count + 2]:
        flag = False
        vt100.gotoxy(h // 2, w // 3, 'GAME OVER')
        vt100.cursor('display')
        os.system("stty echo")

def SnakeRun():
    '''
    游戏运行步骤
    '''
    show_bg()
    while flag:
        move()
        Snake()
        vt100.gotoxy(yf, xf, '@')
        GameOver()
        time.sleep(0.3 / (count / 10 + 1))

def SnakeStart():
    '''
    开启新线程运行游戏
    '''
    init()
    threads = []
    t1 = threading.Thread(target = InputKey)
    threads.append(t1)
    t2 = threading.Thread(target = SnakeRun)
    threads.append(t2)
    for t in threads:
        t.setDaemon(True)
        t.start()
    while flag:
        time.sleep(2)

SnakeStart()


